import { _decorator, Component, find, Input, input, instantiate, KeyCode, Label, Node, Slider, Sprite, SpriteFrame, tween, Tween, v3,director, ToggleContainer, EventHandler, Toggle, ToggleComponent, __private } from 'cc';
import { WsMgr } from './TCP/WsMgr';
import { NetDefine } from './Cmd/NetDefine';
import { GameResult } from './Cmd/GameResult';
import { Utils } from './Common/Utils';
import AudioMgr from './Common/AudioMgr';
import { Press } from './Press';
import HelloPlayer from './HelloPlayer';
import { Config } from './Common/Config';
import { TableMode } from './TableMode';
import { ToastMgr } from './Common/ToastMgr';
import { GameList20 } from './GameList20';
import { GameList } from './GameList/GameList';
import { MatchRanking } from './MatchRanking/MatchRanking';
import { RankingResult } from './Cmd/RankingResult';
const { ccclass, property } = _decorator;

type ItemNode = { icon: Sprite, count: Label, blink: Node };

@ccclass('Turntable')
export class Turntable extends Component {

    @property({ type: SpriteFrame })
    iconSpriteFrame1: SpriteFrame = null;
   
    @property({ type: Label })
    betLab: Label = null;

    @property({ type: Label })
    userScore: Label = null;

    @property({ type: Label })
    getPrizeBig: Label = null;

    @property({ type: Label })
    getPrizeCenter: Label = null;

    @property({ type: Label })
    getPrizeSmall: Label = null;

    @property({ type: Label })
    winUpTo: Label = null;

    @property({ type: Slider })
    slider :Slider;

    @property({ type: Node })
    lightNode: Node = null;
    @property({ type: Node })
    lightNode2: Node = null;

    @property({ type: Node })
    Settings: Node = null;

    @property({ type: Node })
    Desc: Node = null;

    @property({ type: Node })
    List: Node = null;

    @property({ type: Node })
    matchRankingNode: Node = null;

    @property({ type: Label })
    rankingLable: Label = null;

    @property({ type: Label })
    playingLable: Label = null;

    @property({ type: Sprite })
    gameIconSprite: Sprite = null;

    @property({ type: [SpriteFrame] })
    gameIcon: SpriteFrame[] = [];

    @property({ type: Node })
    RankingNode: Node = null;
   

    private ItemNodes: ItemNode[] = [];
    private TurntableNode: Node;
    private TurntableNodeInnerRing: Node;
    private blinkNode: Node;


    private betRatio=[1,2,5,10,20,50,100,200,500,1000,2000,5000];
    private roomRatio=1000;
    private betRatioIndex=0;
    private userScoreNumber:number=0;
   
    private DropLibs = [
        //编号,倍率,转盘位置
        {id:0, count:1.95,  pos:0},
        {id:1, count:1.95,  pos:1},
        {id:2, count:1.95, pos:2},
        {id:3, count:1.95,  pos:3},
        {id:4, count:1.95, pos:4},
        {id:5, count:1.95, pos:5},
        {id:6, count:1.95, pos:6},
        {id:7, count:1.95,  pos:7},    
       
       ];//特殊



    private isDroping: boolean = true;//转动标记，该游戏自动，只有开奖的时候停止转动
    private starAnima: boolean = false;//开始数字特效
    private isSendCmd: boolean = true;//允许发送押注命令


    private isAuto: boolean = false;//自动标记
    private light: boolean = false;
    private wsSrc: WsMgr ;
    private audioSrc: AudioMgr;
    private press:Press;
    private helloPlayer:HelloPlayer;
    private toastSrc:ToastMgr;
    private gameList20:GameList20;
    private gameList:GameList;
    private matchRanking:MatchRanking;

    private lightAnima;
   
    private show(nd: Node): void {
        nd.active = true;
    }

    private hide(nd: Node): void {
        nd.active = false;
    }
   

    start() {
   
        this.TurntableNode = find("Canvas/Node/Turntable/TurntableNode");
        this. TurntableNodeInnerRing=find("Canvas/Node/Turntable/TurntablePointer/center");
        this. blinkNode=find("Canvas/Node/Turntable/TurntablePointer/blink");
        let length = this.DropLibs.length;
        for (let i = 0; i < length; i++) {
            let dropLib = this.DropLibs[i];
            let node: Node;
            if (i == 0) {
                node = this.TurntableNode.children[0];
            }
            else {
                node = instantiate(this.TurntableNode.children[0]);
                this.TurntableNode.addChild(node);
            }
            this.ItemNodes.push({ icon: node.getComponentsInChildren(Sprite)[1], count: node.getComponentInChildren(Label),blink: node.getChildByName('blink')  });

            
            node.angle = -360 / length * i;

        }

        this.updatePrize();

        // 监听滑动事件
        this.slider.node.on('slide', this.callback, this);

        input.on(Input.EventType.KEY_DOWN, event => {
            if (event.keyCode == KeyCode.SPACE) {
               
               
            }
        })

      this. lightAnima=  setInterval(() => {
           this.light=!this.light
           if (this.light) {
            this.lightNode.active=true;
            this.lightNode2.active=false;
           }else{
            this.lightNode2.active=true;
            this.lightNode.active=false;
           }
          
        }, 500)

        
       setInterval(() => {
       
        if (this.isDroping) {//可以转动
            this.TurntableNode.angle+=20;
            this.TurntableNodeInnerRing.angle-=10;
            this. blinkNode.active=false;
            for (let i = 0; i < this.ItemNodes.length; i++) {
                this.ItemNodes[i].count.string=""; 
               }
        }   

     }, 50)

   

      
    }
      callback(slider: Slider) {
        const value =Math.floor(slider.progress*(this.betRatio.length-1)) ;
        this.betRatioIndex=value;
        this.updatePrize();
     }

    onLoad(){
        this.wsSrc = WsMgr.getInstance();
        this.wsSrc.initGameMgr(this);
        this.audioSrc = this.getComponentInChildren(AudioMgr);
        this.press = this.getComponent(Press);
        this.press.add(this);
 

        this.helloPlayer = this.getComponent(HelloPlayer);
        this.toastSrc=this.getComponent(ToastMgr);
        this.gameList20=this.getComponent(GameList20);
        this.gameList=this.getComponent(GameList);
        this.matchRanking=this.getComponent(MatchRanking);
        

        let info=this.wsSrc.getPlayerInfo()
        if (info!=null) {
            this.updateScore( info.score);
          }
        let ranking= this.wsSrc.mRankingResult; 
        this.updateMatchRanking(ranking);
        
        this.betRatio=this.wsSrc.getGameConfig().betArray;//重要代码-加载服务器的押注数组
        this.roomRatio=this.wsSrc.getGameConfig().roomRatio;//重要代码-加载服务器的房间倍率
        console.log('betArray',this. betRatio);

    }
   

    update(deltaTime: number) {

    }
    private autoCount=0;
    public setGameCount(count:number){
    this.autoCount=count;
   // console.log("autoCount",count);
    }

    
    /** 播放音效 */
    private playEffectMisic(adoName: string): void {
        let audioName = this.audioSrc.getAudioName(adoName);
        this.audioSrc.onPlayOneShot(audioName);
    }

    public startGame(){
       
    }

    public autoGame(){
        this. audioSrc.clickEffect();
        this.isAuto= true;
        this.audioSrc.closeAnima();
        this.runAutoGame();  
    }

    public stopAuto(){
        this. audioSrc.clickEffect();
        this.isAuto= false;
        this.autoCount=0;
        
       
    }
    getAutoCounts(){
        return this.autoCount;
    }
    setAutoCounts(autoCount:number){
        return this.autoCount=autoCount;
    }
    getAutoFlag(){
        return this.isAuto;
    }

    public runAutoGame(){
        if (this.isAuto) {
            if (this. autoCount<=0){
                this.isAuto= false;
                return;
            }
            this.startGame(); 
           // console.log('autoCount=', this.autoCount);
            this. autoCount--;
        }
    }
    

     getRandomInt(min: number, max: number): number {
        return Math.floor(Math.random() * (max - min)) + min;
      }
     
     /**更新获得奖励分数 */
    public  updatePrize(){ 
        let bet=this.betRatio[ this.betRatioIndex]*this.roomRatio;
        let odds=WsMgr.getInstance().getGameConfig().redOdds;
        this.betLab.string=''+Utils.num1000(bet);
        this.winUpTo.string=''+Utils.num1000(Math.floor(bet*odds));
        this.slider.progress= this.betRatioIndex/this.betRatio.length;
    }

     
    /***Url裁剪方法 */
    public getRequest() {
        var url = location.search; //获取url中"?"符后的字串
        var theRequest = new Object();
        if (url.indexOf("?") != -1) {
            var str = url.substr(1);
            var strs = str.split("&");
            for (var i = 0; i < strs.length; i++) {
                theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
            }
        }
        return theRequest;
    }

    public add(){
    this. audioSrc.clickEffect();
     // if (this.droping) return;
       if (this.betRatioIndex<this.betRatio.length-1) {
        this.betRatioIndex++;
       }
       this.updatePrize();
    }
    public minus(){
        this. audioSrc.clickEffect();
      //  if (this.droping) return;
        if (this.betRatioIndex>0) {
            this.betRatioIndex--;
           }   
        this.updatePrize();
    }
    public updateScore(score:number){
        this.userScoreNumber=score;
        this.userScore.string=''+Utils.num1000(score);
    }

   public prizeAnima(result:GameResult){

    //展示分数特效
    let addScore=result.prize;
    let t=addScore/20;//分割成20等份，2秒内展示
    let start=0;
    let ratio=result.prize/result.fee;//玩家中奖倍数
    let score=result.score+result.prize;//最后分数
    let time=0;//顺序任务
   
    if (ratio==0) {
        this. playEffectMisic('try_again');
    }else{
        this. playEffectMisic('win_bg');
    }

        //播放动画特效
        if (ratio>=50) {//50倍以上大奖
            this.helloPlayer.playBigWin()   
        }else if(ratio>=1){//1倍以上中奖
            this.helloPlayer.playCenterWin()   
        }else if(ratio>0){//小奖
            this.helloPlayer.playSmallWin()  
        }

        const intervalId = setInterval(() => {
                start+=t;

                time+=100;
                if (!this.starAnima) {//关闭分数更新动画
                  //立即结算
                 this.updateGameSocre(score,result.prize)
                 this.helloPlayer.stop();
                 this.runAutoGame();
                 clearInterval(intervalId);
                 console.log('stop anima');
                 return;
                }

                if (time==5000||ratio==0) {//5秒后结算分数
                    this.updateGameSocre(score,result.prize)
                }
                if (time==6000||ratio==0) {//6秒后结束
                    this.starAnima=false;//停止动画
                    this.runAutoGame();
                    clearInterval(intervalId); 
                }

                if (start>addScore) {
                    start=addScore;
                } 
                start =Math.ceil(start);//向上取整显示数据
               if(time<=2200&&start!=0){
                    //播放数字特效
                  if (ratio>=50) {//50倍以上大奖
                      this.getPrizeBig.string=Utils.num1000k2(start); 
                   }else if(ratio>=1){//1倍以上中奖
                    this.getPrizeCenter.string=Utils.num1000k2(start);
                   }else if(ratio>0){//小奖
                    this.getPrizeSmall.string=Utils.num1000k2(start);
                   }
                   this. playEffectMisic('win'); 
                }
                }, 100); 


   } 
   public prizeAnima2(result:GameResult){
   let node= this.ItemNodes[result.item].blink;
   let blink=true;
   this. playEffectMisic('stop'); 
   let count=0;
   let intervalId=  setInterval(() => {
        count++;
        if ( count<=6) {
            node.active=blink//;
            blink=!blink;    
        }else{
            node.active=false//;
            clearInterval(intervalId); 
        }
       
     }, 300)

   } 

   

   public UIMessage(sub: number, cmd) {
    switch (sub) {
        case NetDefine.GAME_C_SUB_BET_RETURN:
            let  result: GameResult; 
            result=cmd;
           // this.isSendCmd=true;//返回后才可以解锁发送
            if (result!=null) {
                this.stopRun(result);
                console.log('order return=', result);
            }else{//订单提交失败
                this.toastSrc.show('Insufficient score, please recharge',3);
                this.wsSrc.login();//重新获取一次分数
               // console.log('retry');
                setTimeout(() => {
                    this.runAutoGame();
                }, 3000);
            }
           
            break;
            case NetDefine.GAME_C_SUB_ENTER_ROOM_RETURN:
                let info=this.wsSrc.getPlayerInfo()
             if (info!=null) {
              this.updateScore( info.score);
             }
                break;

            case NetDefine.GAME_SUB_GAME_CONFIG:
                    //同步服务器的配置信息，刷新页面
                this. betRatioIndex=0;
                this. betRatio=this.wsSrc.getGameConfig().betArray;//重要代码-加载服务器的押注数组
                this.roomRatio=this.wsSrc.getGameConfig().roomRatio;//重要代码-加载服务器的房间倍率
                this.updatePrize();
    
                break;
    
        default:
            break;
    }
   }


  public onClickShowSettings(){
    this. audioSrc.clickEffect();
   this.audioSrc.onClickShowSettings();
  }

  public onClickShowGameDesc(){
    this. audioSrc.clickEffect();
    this.show(this.Desc);
   }
   public onClickHideGameDesc(){
    this. audioSrc.clickEffect();
    this.hide(this.Desc);
   }

   public onClickShowGameList(){
    this. audioSrc.clickEffect();
    this.show(this.List);
    this.gameList.updateGameList();
   
   }
   public onClickHideGameList(){
    this. audioSrc.clickEffect();
    this.hide(this.List);
   }

   public onClickHideMatchRanking(){
    this. audioSrc.clickEffect();
    this.hide(this.matchRankingNode);
   }

  public getNewScore(){
    this. audioSrc.clickEffect();
    this.wsSrc.login();

  }

 

  private updateGameSocre(score:number,addPrize:number ){
     //立即结算
     this.getPrizeBig.string='';
     this.getPrizeCenter.string='';
     this.getPrizeSmall.string='';
    
     this. updateScore(score)
     if (addPrize!=0) {
     this. playEffectMisic('win'); 
      }
  }
  /**开启动画效果 */
  private isOpenAnimation(){
    return this.audioSrc.isOpenAnimaFlag();
  }
  public back(){
    if (this.isDroping) {
        this.node.destroy();
        director.loadScene(Config.SCENE.PLAZA); 
    }else{
        //游戏结束后，再返回上一界面
        this.toastSrc.show('The lottery is drawing, please wait.',3);
    }
    
  }

  protected onDestroy(): void {
    
      clearInterval(this.lightAnima)
  }
/** 停止转动，开奖 */

  private stopRun(result:GameResult){
    this.updateScore(result.score);
    this.TurntableNode.angle=result.item*45;
    this.isDroping=false;//开奖过程，需要停止转动
    this.starAnima=true;//收到结果，开启特效开关
   
    this. prizeAnima2(result)//中奖闪烁
    this.gameList20.updateList();//更新游戏记录数据

    for (let i = 0; i < this.ItemNodes.length; i++) {//显示中奖分数
        this.ItemNodes[i].count.string="";
         if (result.item==1) {
          if (i%2==1&&result.prize>0) {
            this.ItemNodes[i].count.string="x"+Utils.num1000(result.prize);   
          }  
         }else{
            if (i%2==0&&result.prize>0) {
                this.ItemNodes[i].count.string="x"+Utils.num1000(result.prize);   
              } 
         }
        
       }
     
    
     this.prizeAnimaSetTimeout=setTimeout(() => {//延时300ms开始中奖动画
   
        if ( this.isOpenAnimation()) {
        this. prizeAnima(result);//中奖动画   
       }else{
        let score=result.score+result.prize;
        this.updateGameSocre(score,result.prize);
       }
        }, 300);

     this. autoDropingSetTimeout=setTimeout(() => {
            this.isDroping=true;//中奖则，5.7s继续自动转动，否则2s自动转动
            },this.isOpenAnimation()&&result.prize>0? 5700:2000);

  }
  private prizeAnimaSetTimeout=null;
  private autoDropingSetTimeout=null;
  
  onClickRed(){
 
    this.sendBet(1);
  }

  onClickBlack(){
    
    this.sendBet(2);
   
  }

  onClickStopAnima(){
    
   
    this.helloPlayer.stop();
    if (this.starAnima) {//如果已经开奖，点击了开始，则可以立即结束动画
      //结算分数
      console.log('stop anima,clear... ');
      this.starAnima=false;//关闭动画
      this.isDroping=true;//开始转动
      clearTimeout(this.prizeAnimaSetTimeout);
      clearTimeout(this.autoDropingSetTimeout);
    }
   
  }


  public sendBet(isRed:number){

    this. audioSrc.clickEffect()
    this.helloPlayer.stop();
    if (this.starAnima) {//如果已经开奖，点击了开始，则可以立即结束动画
      //结算分数
      console.log('stop anima,clear... ');
      this.starAnima=false;//关闭动画
      this.isDroping=true;//开始转动
      clearTimeout(this.prizeAnimaSetTimeout);
      clearTimeout(this.autoDropingSetTimeout);
      return
    }
   
    
    if (!this.isDroping) {//转动才能发送游戏指令，否则返回
        console.log('isStop,waitting... ');
        return
     }

     if (!this.isSendCmd) {//上一条指令还在发送中，需要等待
        console.log('isSendCmd,waitting... ');
        return
     }
    
      var bet:number=this.betRatio[ this.betRatioIndex]*this.roomRatio;
      if (this.userScoreNumber-bet<0) {
         // alert('Insufficient score, please recharge');
          this.toastSrc.show('Insufficient score, please recharge',3);
          //console.log('please recharge');
          return    
      }

      this.isSendCmd = false;//发送中，锁定
      setTimeout(() => {this.isSendCmd=true;},3000);//3秒后自动解锁发送
      this.wsSrc.bet(this.betRatioIndex,this.wsSrc.getTableType(),isRed);   

  }

   public getMatchRanking(){
    this.wsSrc.getMatchRanking();
   }
   public showMatchRanking(ranking :RankingResult[]){
    this.show(this.matchRankingNode);
    this.matchRanking.updateGameList(ranking);
   }
   public updateMatchRanking(ranking :RankingResult){
    let isShow=this.wsSrc.getLoginInfo().viewingTableId=="1";
    this.rankingLable.node.active=isShow;
    this.playingLable.node.active=isShow;
    this.gameIconSprite.spriteFrame=this.gameIcon[isShow?1:0]
    this.RankingNode.parent.active=isShow;
    //更新自己
    if (ranking!=null) {
        this.rankingLable.string=ranking.rankingId+"/1000";
        this.playingLable.string=ranking.match_limit+"/"+ranking.match_limit_config;
    }
    
   }
   public closeRanking(){
    this.hide(this.RankingNode);
   }
   public showRanking(){
    this.show(this.RankingNode);
   }

}


